package cn.harry.modular.sys.controller;

import cn.harry.common.annotation.SysLog;
import cn.harry.common.api.R;
import cn.harry.common.enums.BusinessType;
import cn.harry.modular.sys.domain.SysConfig;
import cn.harry.modular.sys.enums.CacheConstants;
import cn.harry.modular.sys.service.SysConfigService;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * ClassName: SysConfigController Description: 系统配置信息表/枚举值表
 *
 * @author honghh Date 2020/02/18 13:57 Copyright (C) www.tech-harry.cn
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@Tag(name = "sys-config 系统配置信息")
@RequestMapping("/sys/config")
public class SysConfigController {

    private final SysConfigService sysConfigService;


    @Operation(summary = "list 分页列表")
    @Parameters({
            @Parameter(name = "current", description = "当前页", required = true, example = "1"),
            @Parameter(name = "size", description = "每页显示条数", required = true, example = "10")
    })
    @PreAuthorize("@ss.hasPermission('system:config:list')")
    @GetMapping(value = "/list")
    public R<IPage<SysConfig>> list(
            @Parameter(hidden = true) Page<SysConfig> page, SysConfig sysConfig) {
        return R.success(sysConfigService.page(page, Wrappers.lambdaQuery(sysConfig)));
    }

    @Operation(summary = "{id} 根据id获取详情")
    @PreAuthorize("@ss.hasPermission('system:config:query')")
    @GetMapping(value = "/{id}")
    public R<SysConfig> getById(@PathVariable Long id) {
        return R.success(sysConfigService.getById(id));
    }

    @Operation(summary = "getKeyToValue/{paramKey} 根据key获取value")
    @PreAuthorize("@ss.hasPermission('system:config:query')")
    @GetMapping(value = "/getKeyToValue/{paramKey}")
    public R<String> getKeyToValue(@PathVariable String paramKey) {
        return R.success(sysConfigService.getKeyToValue(paramKey));
    }

    @Operation(summary = "新增")
    @PreAuthorize("@ss.hasPermission('system:config:add')")
    @SysLog(title = "参数管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R<Integer> save(@RequestBody SysConfig sysConfig) {
        return sysConfigService.save(sysConfig) ? R.success() : R.failed();
    }

    @Operation(summary = "更新")
    @PreAuthorize("@ss.hasPermission('system:config:edit')")
    @SysLog(title = "参数管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @CacheEvict(value = CacheConstants.PARAMS_DETAILS, key = "#sysConfig.paramKey")
    public R<Integer> update(@RequestBody SysConfig sysConfig) {
        return sysConfigService.updateById(sysConfig) ? R.success() : R.failed();
    }

    @Operation(summary = "删除")
    @SysLog(title = "参数管理", businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/{ids}")
    @PreAuthorize("@ss.hasPermission('system:config:remove')")
    @CacheEvict(value = CacheConstants.PARAMS_DETAILS, allEntries = true)
    public R<Integer> deleteByIds(@Parameter(description = "多个以英文逗号(,)拼接") @PathVariable Long[] ids) {
        return sysConfigService.removeBatchByIds(Arrays.asList(ids)) ? R.success() : R.failed();
    }

    @Operation(summary = "refreshCache 刷新参数缓存")
    @PreAuthorize("@ss.hasPermission('system:config:remove')")
    @SysLog(title = "参数管理", businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/refreshCache")
    @CacheEvict(value = CacheConstants.PARAMS_DETAILS, allEntries = true)
    public R<Integer> refreshCache() {
        return R.success();
    }

    @Operation(summary = "export 导出")
    @PreAuthorize("@ss.hasPermission('system:config:export')")
    @SysLog(title = "参数管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public R export(HttpServletResponse response, SysConfig sysConfig) {
        List<SysConfig> list = sysConfigService.getExportList(sysConfig);
        try {
            EasyExcel.write(response.getOutputStream(), SysConfig.class).sheet("参数管理").doWrite(list);
            return R.success();
        } catch (IOException e) {
            log.error("导出失败,error={}", e.getMessage(), e);
        }
        return R.failed();
    }

}
